package org.abratuhi.kvngroupware.network;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class Message {

	/**/
	public Document d;

	/**/
	public Message(){
		Element root = new Element("message");
		d = new Document(root);
	}
	
	/*public Message(Element message){
		d = new Document(message);
	}*/
	
	public static Message fromMessage(String s){
		Message m = new Message();
		m.fromString(s);
		return m;
	}
	
	public String toString(){
		XMLOutputter xmlout = new XMLOutputter();
		StringWriter sw = new StringWriter();
		try {
			xmlout.output(d, sw);
			return sw.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void fromString(String s){
		SAXBuilder saxb = new SAXBuilder();
		StringReader sr = new StringReader(s);
		try {
			d = saxb.build(sr);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public Element getRoot(){
		return this.d.getRootElement();
	}
	
	/*public Message(String name,
			String attrString,
			String valueString,
			String text,
			Element[] contents){
		Element me = new Element("message");
		me.setAttribute("application", "kvngroupware");
		me.addContent(createElement(name, attrString, valueString, text, contents));
		d = new Document(me);
	}*/
	
	/*public Message(String name,
			String[] attrs,
			String[] values,
			String text,
			Element[] contents){
		Element me = new Element("message");
		me.setAttribute("application", "kvngroupware");
		me.addContent(createElement(name, attrs, values, text, contents));
		d = new Document(me);
	}*/
	
	/*private Element createElement(
			String name,
			String attrString,
			String valueString,
			String text,
			Element[] contents){
		String[] attrs = attrString.split(",");
		String[] values = valueString.split(",");
		Element el = new Element(name);
		el.setText(text);
		for(int i=0; i<contents.length; i++)
			el.addContent(contents[i]);
		for(int i=0; i<attrs.length; i++)
			el.setAttribute(attrs[i], values[i]);
		return el;
	}*/
	
	/*private Element createElement(
			String name,
			String[] attrs,
			String[] values,
			String text,
			Element[] contents){
		Element el = new Element(name);
		el.setText(text);
		for(int i=0; i<contents.length; i++)
			el.addContent(contents[i]);
		for(int i=0; i<attrs.length; i++)
			el.setAttribute(attrs[i], values[i]);
		return el;
	}*/

}
